package okhttp3.internal.platform.ohos;
import okhttp3.Protocol;
import okhttp3.internal.platform.Platform;
import org.conscrypt.Conscrypt;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

public class Ohos10SocketAdapter implements SocketAdapter {
    private Companion companion = new Companion();

    @Override
    public Boolean matchesSocket(SSLSocket sslSocket) {
        Conscrypt.checkAvailability();
        return SSLSockets.isSupportedSocket(sslSocket);
    }

    @Override
    public Boolean isSupported() {
        return companion.isSupported();
    }

    @Override
    public String getSelectedProtocol(SSLSocket sslSocket) {
        return "";
    }

    @Override
    public void configureTlsExtensions(SSLSocket sslSocket, String hostname, List<Protocol> protocols) {
        try {
            SSLSockets.setUseSessionTickets(sslSocket, true);

            SSLParameters sslParameters = sslSocket.getSSLParameters();

            sslSocket.setSSLParameters(sslParameters);
        } catch (IllegalArgumentException iae) {
            iae.fillInStackTrace();
        }
    }


    @Override
    public X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    @Override
    public Boolean matchesSocketFactory(SSLSocketFactory sslSocketFactory) {
        return false;
    }

    public class Companion {
        public SocketAdapter buildIfSupported() {
            return (isSupported()) ? Ohos10SocketAdapter.this : null;
        }
        public Boolean isSupported() {
            if (Platform.isOhos()) {
                return true;
            }
            return false;
        }
    }
}

